<template>
  <el-card class="page-container">
    <template #header>
        <div class="header">
            <span>{{ titleName }}</span>
        </div>
    </template>
    <el-form inline>
      <el-form-item label="设备名称">
        <el-input v-model="searchDeviceName" placeholder="输入设备名称" clearable style="width: 180px" />
      </el-form-item>
      <el-form-item label="设备型号">
        <el-input v-model="searchDeviceModel" placeholder="输入设备型号" clearable style="width: 180px" />
      </el-form-item>
      <el-form-item label="类别">
        <el-input v-model="searchCategory" placeholder="输入类别" clearable style="width: 180px" />
      </el-form-item>
      <el-form-item label="使用科室">
        <el-input v-model="searchDept" placeholder="输入科室名称" clearable style="width: 200px" />
      </el-form-item>
      <el-form-item label="设备状态">
        <el-select
          v-model="searchStatus"
          placeholder="请选择状态"
          clearable
          style="width: 180px"
        >
          <el-option v-for="opt in statusFilterOptions" :key="opt.value" :label="opt.label" :value="opt.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="getDataListWithCondition">查询</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="deviceList" style="width: 100%" v-loading="loading">
      
      <!-- 常规字段 -->
      <el-table-column
        v-for="field in ListFields"
        :key="field.prop"
        :prop="field.prop"
        :label="field.label"
        :width="field.width"
      >
      <template #default="{ row }">
        <template v-if="field.slot">
          <!-- 自定义状态列 -->
          <span class="status-dot" :style="{ backgroundColor: statusDotColor(row.status) }"></span>
          <span class="status-text">{{ statusLabel(row.status) }}</span>
        </template>
        <template v-else>
          {{ field.formatter ? field.formatter(row[field.prop]) : row[field.prop] }}
        </template>
      </template>
      </el-table-column>

      <!-- 状态变更操作 -->
      <el-table-column label="状态变更" width="120" align="center">
        <template #default="{ row }">
          <el-tooltip content="更改设备状态" placement="top">
            <el-icon
              :class="['status-edit-icon', { disabled: [4,5,6,7].includes(row.status) }]"
              @click="!([4,5,6,7].includes(row.status)) && openStatusChangeBox(row)"
            >
              <Tools />
            </el-icon>
          </el-tooltip>
        </template>
      </el-table-column>


    </el-table>

    <el-pagination
      v-model:current-page="page"
      v-model:page-size="size"
      :page-sizes="[3, 5, 7, 10]"
      layout="jumper, total, sizes, prev, pager, next"
      background
      :total="total"
      @size-change="onSizeChange"
      @current-change="handlePageChange"
      style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 状态变更弹框 -->
    <el-dialog v-model="statusDialogVisible" title="更改设备状态" width="300px">
      <div style="margin-bottom: 12px">
        设备：<strong>{{ currentRow?.deviceName }}</strong>
      </div>
      <div style="margin-bottom: 20px">
        当前状态：<span :style="{ color: statusDotColor(currentRow?.status || 0) }">
          {{ statusLabel(currentRow?.status || 0) }}
        </span>
      </div>

      <el-select
        v-model="selectedStatus"
        placeholder="请选择新状态"
        style="width: 100%"
      >
        <el-option
          v-for="opt in statusChangeOptions"
          :key="opt.value"
          :label="opt.label"
          :value="opt.value"
        />
      </el-select>

      <template #footer>
        <el-button @click="statusDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmUpdateStatus">确认</el-button>
      </template>
    </el-dialog>

  </el-card>
</template>

<script setup lang="ts">
import { Tools } from '@element-plus/icons-vue'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { ElMessage } from 'element-plus'
import { getDeviceUsageList, getTodayUsageDuration, updateDeviceUsageStatus } from '@/pages/deviceUse/components/DeviceUse'
import type { DeviceUsageVO } from '@/pages/deviceUse/components/DeviceUse'

type DeviceStatus = 1 | 2 | 3 | 4 | 5 | 6 | 7

const deviceList = ref<DeviceUsageVO[]>([])
const loading = ref(false)
const page = ref(1)
const size = ref(10)
const total = ref(0)
const searchDept = ref('')
const searchDeviceName = ref('')
const searchDeviceModel = ref('')
const searchCategory = ref('')
const titleName = "设备使用情况";
const statusDialogVisible = ref(false)
const currentRow = ref<DeviceUsageVO | null>(null)
const selectedStatus = ref<number | null>(null)
const searchStatus = ref<number | null>(null)
let timer: ReturnType<typeof setInterval> | null = null



// 查询用状态选项（包含所有7个状态）
const statusFilterOptions = [
  { label: '运行中', value: 1 },
  { label: '空闲', value: 2 },
  { label: '故障待维修', value: 3 },
  { label: '维修中', value: 4 },
  { label: '已报废', value: 5 },
  { label: '已注销', value: 6 },
  { label: '维护中', value: 7 }
]

const ListFields = [
  { label: '使用ID', prop: 'usageId', width: '80px'},
  { label: '设备序列号', prop: 'serialNumber', width: '240px'  },

  // 状态列，slot渲染
  { label: '设备状态', prop: 'status', width: '100px', slot: true },

  { label: '设备名称', prop: 'deviceName', width: '150px'},
  { label: '设备型号', prop: 'deviceModel', width: '150px' },
  { label: '类别', prop: 'category', width: '150px' },
  { label: '使用科室', prop: 'department', width: '150px' },
  {
    label: '上次使用时间',
    prop: 'lastStartTime',
    width: '180px',
    formatter: (val: string) => (val ? val : '-')
  },
  { label: '总使用时长(小时)', prop: 'usageDuration', width: '80px'},
  { label: '总使用次数', prop: 'usageTimes', width: '80px'},
  { label: '今日使用时长(小时)', prop: 'todayUsageDuration', width: '80px' },
  // {
  //   label: '创建时间',
  //   prop: 'createTime',
  //   width: '180px',
  //   formatter: (val: string) => (val ? val : '-')
  // }
]


const STATUS_MAP: Record<DeviceStatus, { label: string; color: string }> = {
  1: { label: '运行中', color: '#52C41A' },    // 绿色，活跃正常
  2: { label: '空闲', color: '#A0A0A0' },      // 灰色，待用
  3: { label: '故障待维修', color: '#F5222D' }, // 红色，异常
  4: { label: '维修中', color: '#FA8C16' },    // 橙色，处理中
  5: { label: '已报废', color: '#BFBFBF' },    // 灰偏白，结束
  6: { label: '已注销', color: '#D9D9D9' },    // 灰白，作废
  7: { label: '维护中', color: '#1890FF' }     // 蓝色，维护
}


const statusLabel = (status: number) => {
  return STATUS_MAP[status as DeviceStatus]?.label ?? '-'
}

const statusDotColor = (status: number) => {
  return STATUS_MAP[status as DeviceStatus]?.color ?? '#D3D3D3'
}

const statusChangeOptions = [
  { label: '运行中', value: 1 },
  { label: '空闲', value: 2 },
  { label: '故障待维修', value: 3 }
]

const getDataListWithCondition = async () => {
  loading.value = true
  try {
    const res = await getDeviceUsageList(
      page.value,
      size.value,
      searchDeviceName.value,
      searchDeviceModel.value,
      searchCategory.value,
      searchDept.value,
      searchStatus.value ?? undefined
    )
    deviceList.value = res.data.records || []
    total.value = res.data.total || 0
  } catch (e) {
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}


const resetSearch = () => {
  searchDept.value = ''
  searchDeviceName.value = ''
  searchDeviceModel.value = ''
  searchCategory.value = ''
  searchStatus.value = null
  page.value = 1
  getDataListWithCondition()
}

const handlePageChange = (newPage: number) => {
  page.value = newPage
  getDataListWithCondition()
}

const onSizeChange = (size1: number) => {
  size.value = size1
  getDataListWithCondition()
  ElMessage.success('获取成功')
}

const openStatusChangeBox = (row: DeviceUsageVO) => {
  currentRow.value = row
  selectedStatus.value = row.status
  statusDialogVisible.value = true
}

const confirmUpdateStatus = async () => {
  if (!currentRow.value || selectedStatus.value === null) return
  if (currentRow.value.status === selectedStatus.value) {
    ElMessage.info('状态未变化')
    return
  }

  await updateDeviceUsageStatus(currentRow.value.usageId, selectedStatus.value)
  ElMessage.success('状态更新成功')
  statusDialogVisible.value = false
  getDataListWithCondition()
}

const refreshTodayUsage = async () => {
  try {
    const res = await getTodayUsageDuration()
    const updateList = res.data // [{ usageId: 1, todayUsageDuration: 3.25 }, ...]

    updateList.forEach(({ usageId, todayUsageDuration }) => {
      const item = deviceList.value.find((d) => d.usageId === usageId)
      if (item) {
        item.todayUsageDuration = todayUsageDuration
      }
    })
  } catch {
    console.warn('刷新今日使用时长失败')
  }
}

onMounted(() => {
  getDataListWithCondition()
  refreshTodayUsage()

  // 每36秒刷新今日使用时长 + 获取最新设备列表
  timer = setInterval(() => {
    refreshTodayUsage()
  }, 36 * 1000)
})


onBeforeUnmount(() => {
  if (timer) clearInterval(timer)
})
</script>


<style lang="scss" scoped>
.status-dot {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  margin-right: 4px;
  vertical-align: middle;
}
.status-text {
  font-size: 13px;
  color: #333;
  vertical-align: middle;
}

.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}

.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

/* 状态变更小图标美化 */
.status-edit-icon {
  font-size: 18px;
  color: var(--el-color-primary);
  cursor: pointer;
  transition: color 0.3s;

  &:hover {
    color: #409EFF;
  }

  &.disabled {
    color: #C0C4CC;
    cursor: not-allowed;
  }
}

.editor {
  width: 100%;

  :deep(.ql-editor) {
    min-height: 200px;
  }
}

.my-search-form {
  margin-bottom: 0px !important;
  :deep(.el-form-item) {
    margin-bottom: 1px;
  }
}
</style>
